package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
@Component//todo 扫描包
public class WmTokenFilter extends GenericFilterBean {


    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //todo 获取请求头中的信息
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            //TODO 保存到当前线程
            WmThreadLocalUtils.setUser(wmUser);
            log.info("用户id: {} ,通过wemedia网关登录系统",userId);
        }
        //TODO 没有直接放行
        filterChain.doFilter(servletRequest,servletResponse);
        //TODO 过滤器处理完毕直接清空用户信息
        WmThreadLocalUtils.clear();
    }
}
